Basic Grammar
Data types
Integer: Python can handle integers of arbitrary size (Python 2.x had two types of integers,
int
andlong
, but this distinction is not very meaningful for Python, so in Python 3.x integers are now only int), and supports binary (e.g.0b100
, which converts to decimal as 4), octal (e.g.0o100
, which translates to 64 in decimal), decimal (100
) and hexadecimal (0x100
, which translates to 256 in decimal) representations.Floating point: Floating point numbers are also known as decimals, so called because the position of the decimal point of a floating point number is variable when expressed in scientific notation, and floating point numbers support scientific notation (e.g.
1.23456e2
) in addition to mathematical writing (e.g.123.456
).Strings: Strings are arbitrary text enclosed in single or double quotes, such as
'hello'' and
"hello"`, strings are also available in raw string representation, byte string representation, Unicode string representation and can be written in multi-line form (starting with three single or three double quotes and ending with three single or three double quotes).Boolean: Boolean values have only two values,
True
andFalse
, eitherTrue
orFalse
. In Python, Boolean values can be expressed directly asTrue
andFalse
(please note the case), or they can be calculated by Boolean operations (e.g.3 < 5
produces the Boolean valueTrue
, while2 == 1
will produce the Boolean valueFalse
).The complex type: shaped as
3 + 5j
is the same as the mathematical representation of a complex number, the only difference being that thei
in the imaginary part is replaced byj
. In fact, this type is not commonly used, so it is good to know about it.
Variable naming
Hard and fast rules:
- Variable names consist of letters (broad Unicode characters, excluding special characters), numbers and underscores; numbers cannot begin.
- Case sensitive (an upper case
a
and a lower caseA
are two different variables). - Do not conflict with keywords (words with special meanings, covered later) and system reserved words (e.g. names of functions, modules, etc.).
PEP 8 requires:
- Spell words in lowercase letters, with multiple words connected by underscores.
- Protected instance attributes begin with a single underscore (covered later).
- Private instance attributes begin with two underscores (more on this later).
Using type() to check the type of a variable
The built-in functions in Python perform conversions on variable types.
int()
: converts a numeric value or string to an integer, you can specify the binary.float()
: converts a string to a floating point number.str()
: converts a specified object to string form, with the possibility of specifying an encoding.chr()
: converts an integer to the string corresponding to that encoding (one character).ord()
: converts a string (a character) into the corresponding encoding (an integer).
Operators
operator | description |
---|---|
[] [:] | subscript, slice |
* | exponentiation |
~ + - | Inverse by bit, plus or minus sign |
* / % / | multiply, divide, modulo, integer division |
+ - | add, subtract |
> << | shift right, shift left |
& | by bit with |
^ ` | ` |
<= < > >= | less-than-equal, less-than, greater-than, greater-than-equal |
== `! =`` | equal to, not equal to |
is is not | identity operator |
in not in | member operators |
not or and | logical operators |
= += -= *= /= %= //= **= &= ` | = ^= >>= <<=` |
- In practical development, if you are confused about the precedence of operators, you can use parentheses to ensure that the operations are executed in order. *
Keyword
keyword | description |
---|---|
and | Logical operators. |
as | Create an alias. |
assert | Used for debugging. |
break | exit the loop. |
class | Defines a class. |
continue | Continue to the next iteration of the loop. |
def | Defines a function. |
del | Delete the object. |
elif | Used in conditional statements, equivalent to else if. |
else | Used in conditional statements. |
except | Handles exceptions and how to execute them if they occur. |
False | Boolean value, the result of a comparison operation. |
finally | Handles exceptions, and executes a piece of code whether or not an exception exists. |
for | Creates a for loop. |
from | Import a specific part of the module. |
global | Declare global variables. |
if | Write a conditional statement. |
import | Importing a module. |
in | Check if a value exists in a collection such as a list, tuple, etc. |
is | Tests if two variables are equal. |
lambda | Create anonymous functions. |
None | Indicates a null value. |
nonlocal | Declares a non-local variable. |
not | The logical operator. |
or | The logical operators. |
pass | null statement, a statement that does nothing. |
raise | Raises an exception. |
return | Quit the function and return the value. |
True | Boolean, the result of a comparison operation. |
try | Write try... ...except statements. |
while | Create a while loop. |
with | is used to simplify exception handling. |
yield | ends the function and returns the generator. |
Comments
Single line comments: those starting with # and a space
Multi-line comments: three quotes at the beginning and three quotes at the end
"""
First Python program - hello, world!
A tribute to the great Dennis M. Ritchie
Version: 0.1
Author: ``Luo Hao
"""
# hello world!
print('hello, world!')
print("hello, world!")